package com.hopedove.net.kotlin


import com.hopedove.net.Settings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.ksoap2.SoapEnvelope
import org.ksoap2.serialization.SoapObject
import org.ksoap2.serialization.SoapSerializationEnvelope
import org.ksoap2.transport.HttpTransportSE
import kotlin.concurrent.thread
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class SoapClient(
    private val url: String = Settings.getUrl("type2"),
    private val timeout: Int = Settings.TIMEOUT,
    private val nameSpace: String = Settings.NAME_SPACE
) {

    /***
     * 调用服务端方法
     *
     * @param methodName 服务端的方法名，是 SoapAction 的一部分
     * @param param 对应的参数
     * @return 返回服务的响应，是 Soap 的消息文本
     */
    suspend fun makeCall(methodName: String, param: String): CallResult<String> =
        withContext(Dispatchers.IO) {
            val request = SoapObject(nameSpace, methodName)
            if (param.isNotEmpty()) {
                request.addProperty("arg0", param)
            }
            val envelope = SoapSerializationEnvelope(SoapEnvelope.VER11).apply {
                dotNet = false
                setOutputSoapObject(request)
            }

            val httpTransport = HttpTransportSE(url, timeout).apply { debug = true }

            suspendCoroutine { cont ->
                thread {
                    try {
                        httpTransport.call("\"$nameSpace$methodName\"", envelope)
                        if (envelope.response != null) {
                            val response = envelope.response.toString()
                            cont.resume(SuccessResult(response))
                        } else {
                            cont.resume(ErrorResult("response is null"))
                        }
                    } catch (e: Exception) {
                        cont.resume(ErrorResult(e.toString()))
                    }
                }
            }
        }

}